<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { getAccessToken } from '../utils/auth.js'
import { useUserWebSocketStore } from '../stores/websocket'

const router = useRouter()
const wsStore = useUserWebSocketStore()
const loading = ref(false)
const userInfo = ref(null)

// 返回个人中心
const goBack = () => {
  router.push('/profile')
}

// 返回个人中心
const goToProfile = () => {
  router.push('/profile')
}

// 加载用户信息
const loadUserInfo = async () => {
  const token = getAccessToken()
  if (!token) {
    showToast('请先登录')
    router.push('/user/login')
    return
  }

  loading.value = true
  try {
    const response = await fetch('http://localhost:8000/user/idcard/status', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    const result = await response.json()

    if (result.code === 200 && result.data) {
      userInfo.value = {
        nickname: result.data.nickname || '用户',
        avatar: result.data.avatar,
        phone: result.data.phone || ''
      }
    }
  } catch (error) {
    console.error('获取用户信息出错:', error)
  } finally {
    loading.value = false
  }
}

// WebSocket 消息处理
const handleIdentityMessage = (messageData) => {
  try {
    // 处理 OCR 识别结果
    if (messageData.type === 'ocr_complete') {
      console.log('身份证识别完成:', messageData)
      // 更新本地存储的认证状态
      localStorage.setItem('user_verified', 'true')
      // 收到消息后关闭 WebSocket 连接
      wsStore.disconnectIdentityVerification()
      console.log('PendingVerificationView: 身份认证完成，已关闭 WebSocket 连接')
    } else if (messageData.type === 'ocr_failed') {
      console.log('身份证识别失败:', messageData)
      // 失败时不做任何提示，只记录日志
    }
  } catch (error) {
    console.error('处理实名认证消息失败:', error)
  }
}

// 初始化 WebSocket 连接
const initWebSocket = () => {
  // 确保用户已登录
  const userId = localStorage.getItem('user_id')
  if (!userId) {
    console.warn('用户未登录，无法建立实名认证 WebSocket 连接')
    return
  }

  // 如果连接已存在，直接注册消息处理器；否则建立新连接
  if (!wsStore.isIdentityConnected) {
    wsStore.initIdentityVerification()
  }

  // 注册消息处理器
  wsStore.registerIdentityMessageHandler('pending_verification', handleIdentityMessage)
}

onMounted(() => {
  loadUserInfo()
  // 初始化 WebSocket 连接（如果还未建立）
  initWebSocket()
})

onUnmounted(() => {
  // 移除消息处理器（但不断开连接，因为可能还需要在其他页面接收消息）
  wsStore.unregisterIdentityMessageHandler('pending_verification')
  // 注意：不在这里断开连接，让连接保持以便接收审核结果
})
</script>

<template>
  <div class="pending-page">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="身份认证"
      left-arrow
      @click-left="goBack"
      class="nav-bar"
    />

    <!-- 内容区域 -->
    <div class="content">
      <!-- 审核中状态 -->
      <div class="status-section">
        <div class="status-icon-wrapper">
          <van-icon name="clock-o" size="80" color="#FF9800" />
        </div>
        <h2 class="status-title">实名认证审核中</h2>
        <p class="status-desc">您的身份证信息正在审核中，请耐心等待</p>
      </div>

      <!-- 提示信息卡片 -->
      <div class="tips-card">
        <div class="tips-header">
          <van-icon name="info-o" size="18" color="#FF6B00" />
          <span class="tips-title">温馨提示</span>
        </div>
        <div class="tips-content">
          <div class="tip-item">• 审核时间通常为1-3个工作日</div>
          <div class="tip-item">• 审核结果将通过消息通知您</div>
          <div class="tip-item">• 您可以在个人中心查看审核状态</div>
          <div class="tip-item">• 如有疑问，请联系客服咨询</div>
        </div>
      </div>

      <!-- 用户信息卡片 -->
      <div class="info-card" v-if="userInfo">
        <div class="card-header">
          <van-icon name="user-o" size="20" color="#667eea" />
          <span class="card-title">用户信息</span>
        </div>
        <div class="info-list">
          <div class="info-item" v-if="userInfo.nickname">
            <span class="info-label">昵称</span>
            <span class="info-value">{{ userInfo.nickname }}</span>
          </div>
          <div class="info-item" v-if="userInfo.phone">
            <span class="info-label">手机号</span>
            <span class="info-value">{{ userInfo.phone }}</span>
          </div>
          <div class="info-item">
            <span class="info-label">认证状态</span>
            <span class="info-value pending">审核中</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="footer-section">
      <van-button
        type="primary"
        block
        round
        @click="goToProfile"
        class="back-btn"
      >
        返回个人中心
      </van-button>
    </div>
  </div>
</template>

<style scoped>
.pending-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 100px;
}

/* 导航栏 */
.nav-bar {
  --van-nav-bar-background: white;
  --van-nav-bar-title-text-color: #333;
}

/* 内容区域 */
.content {
  padding: 24px 16px;
}

/* 状态区域 */
.status-section {
  background: white;
  border-radius: 16px;
  padding: 40px 20px;
  text-align: center;
  margin-bottom: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.status-icon-wrapper {
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.status-icon-wrapper .van-icon {
  background: #FFF3E0;
  border-radius: 50%;
  padding: 20px;
}

.status-title {
  font-size: 24px;
  font-weight: 600;
  color: #333;
  margin: 0 0 12px 0;
}

.status-desc {
  font-size: 15px;
  color: #666;
  margin: 0;
}

/* 提示信息卡片 */
.tips-card {
  background: #FFF7E6;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
  border-left: 4px solid #FF6B00;
}

.tips-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.tips-title {
  font-size: 15px;
  font-weight: 600;
  color: #FF6B00;
}

.tips-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tip-item {
  font-size: 13px;
  color: #FF9500;
  line-height: 1.6;
}

/* 信息卡片 */
.info-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-label {
  font-size: 14px;
  color: #999;
}

.info-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.info-value.pending {
  color: #FF9800;
  font-weight: 600;
}

/* 底部按钮 */
.footer-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 12px 16px;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.08);
}

.back-btn {
  --van-button-primary-background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  --van-button-primary-border-color: transparent;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
}
</style>
